// reducer
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { fetchLogin, LoginType } from './loginApi'

// promise处理异步
export const fetchAsyncAction = createAsyncThunk('login/fetchLogin', async (values: LoginType) => {
  const result: any = await fetchLogin(values)
  console.log('result,:------', result)
  if (result.code === -1) {
    return { code: -1, msg: 'fail' }
  }
  return result.data

  // return result.data
})

const loginSlice = createSlice({
  name: 'login',
  initialState: { token: '', loading: false, msg: '' },
  reducers: {
    set_token(state, action) {
      console.log('action:', action)
      state.token = action.payload
    },
  },
  // 处理异步
  extraReducers(builder) {
    builder.addCase(fetchAsyncAction.pending, (state, action) => {
      state.loading = true
    })
    builder.addCase(fetchAsyncAction.fulfilled, (state, action) => {
      console.log('action:-------接受的参数：', action)
      // 登陆成功的状态
      if (action.payload.token) {
        state.token = action.payload.token
        state.loading = false
      } else {
        // 失败
        state.msg = action.payload.msg
        state.loading = false
      }
    })
  },
})

export default loginSlice.reducer

export const { set_token } = loginSlice.actions
